package com.htrq.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.htrq.entity.Page;
import com.htrq.entity.TResource;
import com.htrq.service.TResService;

@Controller
@RequestMapping("jsp/sys")
public class TResController {

	@Resource
	private TResService trService;
	
	/**
	 * 菜单栏数据
	 * 组成菜单树的过滤掉页面操作类权限的数据
	 */
	@RequestMapping("getRight")
	@ResponseBody
	public String getRight(HttpServletRequest request,HttpServletResponse response) throws IOException{
		@SuppressWarnings("unchecked")
		List<TResource> list=(List<TResource>) request.getSession().getAttribute("right");
		String str=JSON.toJSONString(trService.getRight(list));
		response.setContentType("text/html;charset=utf8");
		PrintWriter out= response.getWriter();
		out.print(str);
		return null;
	}
	/**
	 * 赋予权限时候用的带checkbox的资源列表
	 * 树形数据
	 */
	@RequestMapping("getRightBox")
	@ResponseBody
	public String getRightByBox(HttpServletResponse response) throws IOException{
		String str=JSON.toJSONString(trService.getRightByBox());
		response.setContentType("text/html;charset=utf8");
		PrintWriter out= response.getWriter();
		out.print(str);
		return null;
	}
	/**
	 *添加，页面和权限添加 
	 * @throws IOException 
	 */
	@RequestMapping("saveresource")
	@ResponseBody
	public String saveres(HttpServletResponse response,TResource resc) throws IOException{
		boolean flag=trService.saveres(resc);
		response.setContentType("text/html;charset=utf8");
		PrintWriter out = response.getWriter();
		if (flag) {
			out.print("{'success':true,'res':{'result':'添加成功'}}");
		}else{
			out.print("{'success':true,'res':{'result':'添加失败'}}");
		}
		return null;
	}
	/**
	 * 资源列表展示和查询
	 * @throws IOException 
	 */
	@RequestMapping("getAllResByPage")
	public String getAllByPage(HttpServletResponse response,Page page) throws IOException{
		String str=JSON.toJSONString(trService.getAllByPage(page));
		Long count=trService.getTotal();
		String json="{total:"+count+",root:"+str+"}";
		response.setContentType("text/html;charset=utf8");
		PrintWriter out = response.getWriter();
		out.print(json);
		return null;
	}
}
